//
//  tableViewEvent.m
//  Gruphoto
//
//  Created by lithewall on 2/4/13.
//  Copyright (c) 2013 CNC Software. All rights reserved.
//

#import "TableViewEventImages.h"
#import "Photo.h"
#import "EventPhotoCell.h"
#import "PhotoDetailViewController.h"

@implementation TableViewEventImages
-(id)initWithData:(NSArray*)data atFrame:(CGRect)frame{
    self = [super initWithFrame:frame];
    if (self) {
        // Initialization code
        self.delegate = self;
        self.dataSource = self;
        [self createListPhotosbyAdata:(NSArray*)data];
    }
    return self;
}
/*
 photos =     (
 {
 comments =             (
 );
 creator =             {
 name = "Thao Nguyen Huy";
 photo = "/media/user/default-avatar.png";
 "user_id" = 49;
 };
 "image_id" = 24;
 "num_like" = 0;
 source = "/media/event/28d0a0bd-07b9-49da-9fc9-d5311bac0d61.jpg";
 },
 {
 comments =             (
 );
 creator =             {
 name = "Thao Nguyen Huy";
 photo = "/media/user/default-avatar.png";
 "user_id" = 49;
 };
 "image_id" = 25;
 "num_like" = 0;
 source = "/media/event/3f18eec0-b8c6-4056-8686-1417a0935e7f.jpg";
 }
 );
 */

#pragma mark - display content
-(void)createListPhotosbyAdata:(NSArray*)data{
    InfoDisplay = [[NSMutableArray alloc] init];
    listPhotoFilterByFavorite = [[NSMutableArray alloc] init];
    photosInfo = [[NSMutableArray alloc] initWithArray:data];
    listImage = [[NSMutableArray alloc] initWithCapacity:[data count]];
    typeDisplay = TableViewDisplayTypeByNewest;
    [self filterIdByFavorite];
    [InfoDisplay setArray:photosInfo];
}

-(void)filterIdByFavorite{
//    [listPhotoFilterByFavorite setArray:photosInfo];
//    [listPhotoFilterByFavorite addObject:[photosInfo objectAtIndex:0]];
//    for (NSDictionary *onePhotoInfo in photosInfo) {
//        NSLog(@"one data = %@",onePhotoInfo);
//        BOOL hasAdd = NO;
//        for (int i=0; i<[listPhotoFilterByFavorite count]; i++) {
//            NSDictionary *onePhotoInfo1 = [listPhotoFilterByFavorite objectAtIndex:i];
//            NSLog(@"one data = %@",onePhotoInfo1);
//            if ([onePhotoInfo objectForKey:kNumLike]>[onePhotoInfo1 objectForKey:kNumLike]) {
//                [listPhotoFilterByFavorite insertObject:onePhotoInfo atIndex:i];
//                hasAdd = YES;
//            }
//        }
//        if (hasAdd==NO) {
//            [listPhotoFilterByFavorite addObject:onePhotoInfo];
//        }
//    }
    
//    photosInfo
    NSArray *sortedArray = [photosInfo sortedArrayUsingComparator:^NSComparisonResult(id obj1, id obj2) {
        NSDictionary *dict1 = (NSDictionary *)obj1;
        NSDictionary *dict2 = (NSDictionary *)obj2;
        return [[dict1 objectForKey:kNumLike] integerValue] > [[dict2 objectForKey:kNumLike] integerValue];
    }];
    [listPhotoFilterByFavorite setArray:sortedArray];
}

-(void)displayByNewest{
    [InfoDisplay setArray:photosInfo];
    typeDisplay = TableViewDisplayTypeByNewest;
    [listImage removeAllObjects];
    [self reloadData];
}

-(void)displayByMostFavorite{
    [InfoDisplay setArray:listPhotoFilterByFavorite];
    typeDisplay = TableViewDisplayTypeByFilterFavorite;
    [listImage removeAllObjects];
    [self reloadData];
}

-(void)downloadImageAndDisplay{
    /*
     photos =     (
     {
     comments =             (
     );
     creator =             {
     name = "Thao Nguyen Huy";
     photo = "/media/user/default-avatar.png";
     "user_id" = 49;
     };
     "image_id" = 24;
     "num_like" = 0;
     source = "/media/event/28d0a0bd-07b9-49da-9fc9-d5311bac0d61.jpg";
     },
     {
     comments =             (
     );
     creator =             {
     name = "Thao Nguyen Huy";
     photo = "/media/user/default-avatar.png";
     "user_id" = 49;
     };
     "image_id" = 25;
     "num_like" = 0;
     source = "/media/event/3f18eec0-b8c6-4056-8686-1417a0935e7f.jpg";
     }
     );
     */
    /*download image, cache image and display*/
    dispatch_async(dispatch_get_global_queue(0, 0), ^{
        for (int i=0; i<[listImage count];i++) {
            /*
            __block UIActivityIndicatorView *activityIndicator;
            [self.imageView setImageWithURL:self.imageURL placeholderImage:nil options:SDWebImageProgressiveDownload progress:^(NSUInteger receivedSize, long long expectedSize)
             {
                 if (!activityIndicator)
                 {
                     [self.imageView addSubview:activityIndicator = [UIActivityIndicatorView.alloc initWithActivityIndicatorStyle:UIActivityIndicatorViewStyleGray]];
                     activityIndicator.center = self.imageView.center;
                     [activityIndicator startAnimating];
                 }
             }
                                  completed:^(UIImage *image, NSError *error, SDImageCacheType cacheType)
             {
                 [activityIndicator removeFromSuperview];
                 activityIndicator = nil;
             }];
            EventPhotoView *view = [listImage objectAtIndex:i];
            EventPhotoView 
             */
//            EventPhotoView *view = [listImage objectAtIndex:i];
            
        }
    });
}
#pragma mark - UITableViewDataSource
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    int t = [InfoDisplay count]/3;
    return t+([InfoDisplay count]-t*3>0?1:0);
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    static NSString *EventPhotoCellId = @"EventPhotoCell";
        NSLog(@"[InfoDisplay count] = %d",[InfoDisplay count]);
        EventPhotoCell *cell = (EventPhotoCell *)[tableView dequeueReusableCellWithIdentifier:EventPhotoCellId];
        if (cell == nil) {
            cell = [EventPhotoCell cellFromNib];
        }
    for (int i=0;i<[cell.placeHolders count];i++) {
        UIView *holder = [cell.placeHolders objectAtIndex:i];
            CGRect frame = CGRectMake(0, 0, kViewWidth, kViewHeight);
        int k = indexPath.row*3+i;
         NSLog(@"k = %d and [InfoDisplay count] = %d",k,[InfoDisplay count]);
        if (k<[InfoDisplay count]) {
            [self removeSubViewOfView:holder];
            EventPhotoView *view;
                view = [EventPhotoView  viewFromNibWithData:[InfoDisplay objectAtIndex:indexPath.row*3+i]];
                [listImage addObject:view];
                view.delegate = self;
                [view displayImage];
                view.frame = frame;
                view.tag = indexPath.row*3+i;
            dispatch_async(dispatch_get_main_queue(), ^{
                if (typeDisplay == TableViewDisplayTypeByNewest) {
                    [view hideFooter];
                }
                else {
                    [view displayFooter];
                }
            });
            [holder addSubview:view];
        }else{
            if (holder!=nil) {
                [holder removeFromSuperview];
            }
//            holder.hidden = YES;
        }
        }
        return cell;
}

-(CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath{
    return kHeightEventPhotoCell;
}

#pragma mark - UITableViewDelegate
-(void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath{
    //    if (tableView == userTableView) {
    //        UserDetailViewController *userDetailViewController = [[UserDetailViewController alloc] initWithNibName:@"UserDetailViewController" bundle:nil];
    //        [self.navigationController pushViewController:userDetailViewController animated:YES];
    //        [userDetailViewController release];
    //    }
}


#pragma mark - release value
-(void)dealloc{
    [photosInfo release];
    [listPhotoFilterByFavorite release];
    [InfoDisplay release];
    [super dealloc];
}

#pragma mark - EventPhotoView
- (void)didSelectPhotoAtIndex:(NSInteger)index {
    PhotoDetailViewController *photoDetailViewController = [[PhotoDetailViewController alloc] initWithNibName:@"PhotoDetailViewController" bundle:nil];
    photoDetailViewController.currentIndexOfImage = index;
    photoDetailViewController.listImagesData = InfoDisplay;
    photoDetailViewController.info = [[[NSMutableDictionary alloc]initWithDictionary:[InfoDisplay objectAtIndex:index]] autorelease];
    [[self getViewControllerOfView:self].navigationController pushViewController:photoDetailViewController animated:YES];
    [photoDetailViewController release];
}

-(UIViewController*)getViewControllerOfView:(UIView*)view{
    if ([[view nextResponder] isKindOfClass:[UIViewController class]]) {
        return (UIViewController*)[view nextResponder];
    }else{
        return [self getViewControllerOfView:view.superview];
    }
}

-(void)removeSubViewOfView:(UIView*)view{
    NSArray *subViews = view.subviews;
    for (UIView *subView in  subViews) {
        [subView removeFromSuperview];
    }
}
@end
